package com.risk.kernel.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONPath;
import com.risk.common.utils.DateUtils;
import com.risk.common.utils.StringUtils;
import com.risk.kernel.domain.DsCallRecord;
import com.risk.kernel.domain.DsTripartiteAgreement;
import com.risk.kernel.mapper.DsCallRecordMapper;
import com.risk.kernel.mapper.DsTripartiteAgreementMapper;
import com.risk.kernel.service.DsCallRecordService;
import com.risk.kernel.service.IDsTripartiteAgreementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: Liwen
 * @createTime: 2024/12/2
 * @description:
 */
@Service
public class DsCallRecordServiceImpl implements DsCallRecordService {
    @Autowired
    private IDsTripartiteAgreementService agreementService;
    @Autowired
    private DsTripartiteAgreementMapper agreementMapper;
    @Autowired
    private DsCallRecordMapper recordMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public int deleteRecordBath(String[] ids) {
        return recordMapper.deleteRecordBath(ids);
    }

    @Override
    public List<DsCallRecord> selectDsCallRecordList(String searchValue) {
        return recordMapper.selectDsCallRecordList(searchValue);
    }


    @Override
    public String getRepMessage(String reqInfo) {
        JSONObject jsonObject = JSONObject.parseObject(reqInfo);
        String appNo = (String) jsonObject.get("APP_NO");
        if (StringUtils.isEmpty(appNo)) {
            appNo = (String) jsonObject.get("app_no");
        }
        if (StringUtils.isEmpty(appNo)) {
            appNo = (String) jsonObject.get("orderNo");
        }
        if (StringUtils.isEmpty(appNo)) {
            appNo = (String) jsonObject.get("bizNo");
        }
        if (StringUtils.isEmpty(appNo)) {
            appNo = (String) jsonObject.get("biz_no");
        }
        // 是否开启线程数据流
        String key = "threadStreamKey_" + appNo;
        boolean threadUnlock = agreementService.getThreadUnlock();
        if (threadUnlock) {
            String value = redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotEmpty(value)) {
                return value;
            }
        }


        DsTripartiteAgreement agreement = agreementMapper.selectAgreementByAppNo(appNo);
        String rep = "";
        DsCallRecord record = createRecord(appNo, reqInfo);
        if (agreement != null && StringUtils.isNotEmpty(agreement.getRepBody())) {
            rep = agreement.getRepBody();
            record.setCallStatus(1);
            record.setAppCode(agreement.getAppCode());
            record.setModelName(agreement.getModelName());
            record.setRepBody(agreement.getRepBody());
            record.setModelName(agreement.getModelName());
            if (threadUnlock) {
                saveThreadUnlockData(key, JSON.toJSONString(agreement));
            }
        } else {
            record.setRemark("调用失败，未查询到三方记录，请检查是否配置了三方数据源！");
        }
        saveRecord(record);
        return rep;
    }

    @Override
    public String getServiceCode(String serviceCode) {
        // 状态数据
        String key = "wg_" + serviceCode;
        String status = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(status)) {
            status = "3";
            redisTemplate.opsForValue().set(key, status);
        }
        // 是否开启线程数据流
        String threadStreamKey = key + "_" + "threadStreamKey_" + status;
        boolean threadUnlock = agreementService.getThreadUnlock();
        if (threadUnlock) {
            String value = redisTemplate.opsForValue().get(threadStreamKey);
            if (StringUtils.isNotEmpty(value)) {
                return value;
            }
        }
        DsTripartiteAgreement agreement = agreementMapper.getServiceCode(serviceCode, status);
        DsCallRecord record = createRecord("", "");
        String rep = "";
        if (agreement != null && StringUtils.isNotEmpty(agreement.getRepBody())) {
            rep = agreement.getRepBody();
            record.setCallStatus(1);
            record.setRepBody(agreement.getRepBody());
            record.setAppCode(serviceCode);
            record.setModelName(agreement.getModelName());
            if (threadUnlock) {
                saveThreadUnlockData(threadStreamKey, JSON.toJSONString(agreement.getRepBody()));
            }
        } else {
            record.setRemark("调用失败，未查询到三方记录，请检查是否配置了三方数据源！");
        }
        saveRecord(record);
        return rep;
    }


    public void saveRecord(DsCallRecord dsCallRecord) {
        recordMapper.insertIntoCallRecord(dsCallRecord);
    }

    public DsCallRecord createRecord(String appNo, String reqInfo) {
        String jsonString = JSON.toJSONString(reqInfo);
        DsCallRecord dsCallRecord = new DsCallRecord();
        String callName = String.valueOf(JSONPath.eval(jsonString, "$.measures.PROCESS_RESULT"));
        if (StringUtils.isNotEmpty(callName) && !"null".equals(callName)) {
            dsCallRecord.setAppCode(callName);
        }
        dsCallRecord.setAppNo(appNo);
        dsCallRecord.setReqParams(reqInfo);
        dsCallRecord.setCallStatus(2);
        dsCallRecord.setCreateTime(DateUtils.getNowDate());
        return dsCallRecord;
    }


    public String getThreadUnlockData(String key) {
        boolean threadUnlock = agreementService.getThreadUnlock();
        if (threadUnlock) {
            return redisTemplate.opsForValue().get("key");
        }
        return "";
    }

    public void saveThreadUnlockData(String key, String value) {
        redisTemplate.opsForValue().set(key, value, 12, TimeUnit.HOURS);
    }
}

